package com.artfii.hibernate;

import com.artfii.IdGen;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;

/**
 * HIBERNATER 自定义主键 ID 生成
 * @author: lqf 2020-12-23
 */
public class HibernateKeyGen implements IdentifierGenerator {

    @Override
    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
        Object id = Reflections.getFieldValue(object, "id");
        if (null != id) {//如果保存的对象 ID 已经有值，则返回旧 ID 值(分表保存时保证ID值一致性)
            return (Serializable) id;
        } else {
            //生成新的ID值，默认为19位（long)
            return IdGen.ONLY.getDefId();
        }
    }

}
